﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;
using XbdSoft.Client;
using XbdSoft.Contract;
using System.Security.Cryptography;
using System.Windows.Interop;
using System.Threading;
using System.ComponentModel;
using System.Windows.Threading;
using System.Net;
using System.IO;

namespace XbdSoft.WPFVersion
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        #region Const

        private readonly string CookieUrl = "C:\\xbdsoft\\Cookie";
        private const string NameCookieKey = "xbdname";
        private const string PasswordCookieKey = "xbdpwd";
        private const string AutoLoginCookieKey = "xbdautologin";
        private const string RememeberMeCookieKey = "xbdrememberme";
        public const string AutoUpdateExeFileName = "小布叮自动更新.exe";
        #endregion

        #region Ctor

        public LoginWindow()
        {
            InitializeComponent();
            HasLogin = false;
        }
        #endregion

        #region Properties
        public bool HasLogin { get; set; }
        #endregion

        #region Button Events
        private void RegisterHyperlink_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var accountService = new ServiceObject<IAccountService>(Util.AccountServiceAddress))
                {
                    Process.Start(accountService.Object.GetRegisterUrl());
                }
            }
            catch
            {
                Process.Start("http://www.xbd61.com/member.asp");
            }
        }

        private void ForgotPasswordHyperlink_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var accountService = new ServiceObject<IAccountService>(Util.AccountServiceAddress))
                {
                    Process.Start(accountService.Object.GetForgotPasswordUrl());
                }
            }
            catch
            {
                Process.Start("http://www.xbd61.com/User_GetPassword.asp");
            }
        }

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            Login();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        #endregion

        #region Helper
        private void Login()
        {
            var originPassword = PasswordBox.Password;

            using (var accountService = new ServiceObject<IAccountService>(Util.AccountServiceAddress))
            {
                var password = accountService.Object.EncryptByMD5(originPassword);
                if (accountService.Object.Login(UserNameBox.Text, password))
                {
                    HasLogin = true;
                    var expiredDate = RememberPasswordCheckBox.IsChecked == true ? "10-Oct-2722" : "10-Oct-1942";
                    var nameCookieValue = NameCookieKey + "=" + UserNameBox.Text + ";expires=Sat, " + expiredDate + " 00:00:00 GMT";
                    var passwordCookieValue = PasswordCookieKey + "=" + PasswordBox.Password + ";expires=Sat, " + expiredDate + " 00:00:00 GMT";
                    var autoLoginCookieValue = AutoLoginCookieKey + "=" + (AutoLoginCheckBox.IsChecked == true ? "1" : "0") + ";expires=Sat, " + expiredDate + " 00:00:00 GMT";
                    Application.SetCookie(new Uri(CookieUrl), nameCookieValue);//BrowserInteropHelper.Source
                    Application.SetCookie(new Uri(CookieUrl), passwordCookieValue);
                    Application.SetCookie(new Uri(CookieUrl), autoLoginCookieValue);

                    Util.UserName = UserNameBox.Text;
                    Util.Password = PasswordBox.Password;


                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        //NotifyService(UserNameBox.Text, PasswordBox.Password);
                        //Thread.Sleep(6000);
                        Close();
                    }));
                }
                else
                {
                    MessageBox.Show("用户名或密码错误。");
                    UserNameBox.Focus();
                }
            }
        }

        private void NotifyService(string userName, string password)
        {
            //var usepass = "123";
            //if (!string.IsNullOrEmpty(usepass))
            //{
            //    var requestUrl = string.Format("http://www.xbd61.com/api/api_savelogin.asp?username={0}&password={1}&usepass={2}", userName, password, usepass);
            //    var webRequest = HttpWebRequest.Create(requestUrl);
            //    var webResponse = webRequest.GetResponse(); 
            //}
            try
            {
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    var usepass = service.Object.GetUsePassword();
                    if (!string.IsNullOrEmpty(usepass))
                    {
                        var requestUrl = string.Format("http://www.xbd61.com/api/api_savelogin.asp?username={0}&password={1}&usepass={2}", userName, password, usepass);
                        var webRequest = HttpWebRequest.Create(requestUrl) as HttpWebRequest;
                        webRequest.CookieContainer = new CookieContainer();
                        var webResponse = webRequest.GetResponse();
                        using (var stream = webResponse.GetResponseStream())
                        using (var reader = new StreamReader(stream))
                        {
                            //var buffer = new byte[stream.Length];
                            //stream.Read(buffer, 0, (int)stream.Length);
                            var dd = reader.ReadToEnd();
                            dd += "";
                            //var varlue = System.Text.Encoding.Default.GetString(buffer);
                            //stream.Close();
                        }
                    }
                }
            }
            catch { }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (timer != null)
                timer.Stop();
            Login();

        }
        DispatcherTimer timer = null;


        private string GetCookieValue(string cookieValue, string name)
        {
            var cookies = cookieValue.Split(";".ToArray());
            foreach (var cookie in cookies)
            {
                var args = cookie.Trim().Split("=".ToArray());
                if (args.Length > 1 && args[0] == name)
                {
                    return args[1];
                }
            }
            return string.Empty;
        }

        #endregion

        #region Window Load
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerAsync(Dispatcher);
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var dispather = e.Argument as Dispatcher;
            try
            {
                CheckService();

                if (HasNewVersion() && MessageBox.Show("小布叮有新的版本需要更新，您确定要更新吗？", "自动更新程序", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    UpdateLatestVersion();
                }
                
            }
            catch { }
            dispather.BeginInvoke(new Action(
            
                ()=>{
                     MaskBorder.Visibility = System.Windows.Visibility.Collapsed;
                     LoginGrid.Visibility = System.Windows.Visibility.Visible;
                    UserNameBox.Focus();
                    try
                    {
                        var cookieValue = Application.GetCookie(new Uri(CookieUrl)) ?? string.Empty;
                        UserNameBox.Text = GetCookieValue(cookieValue, NameCookieKey);
                        PasswordBox.Password = GetCookieValue(cookieValue, PasswordCookieKey);
                        AutoLoginCheckBox.IsChecked = GetCookieValue(cookieValue, AutoLoginCookieKey) == "1";
                        if (AutoLoginCheckBox.IsChecked == true)
                        {
                            timer = new DispatcherTimer();
                            timer.Interval = TimeSpan.FromSeconds(2);
                            timer.Tick += new EventHandler(timer_Tick);
                            timer.Start();
                        }
                    }
                    catch { }             
                    }
            ));
           
        }

        #endregion

        #region Check Version

        private bool HasNewVersion()
        {
            bool isLatestVersion = false;
            var currentVersion = Application.ResourceAssembly.GetName().Version;
            try
            {
                using (var autoUpdateService = new ServiceObject<IAutoUpdateService>(Util.AutoUpdateServiceAddress))
                {
                    var latestVersionStr = autoUpdateService.Object.GetLatestVersion();
                    if (!String.IsNullOrWhiteSpace(latestVersionStr))
                    {
                        var latestVersion = new Version(latestVersionStr);
                        isLatestVersion = latestVersion.CompareTo(currentVersion) > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
            return isLatestVersion;
        }

        private void UpdateLatestVersion()
        {
            try
            {
                var autoUpdateExeFile = System.IO.Path.Combine(Environment.CurrentDirectory, AutoUpdateExeFileName);
                if (!System.IO.File.Exists(autoUpdateExeFile))
                {
                    MessageBox.Show(string.Format("对不起，没有找到更新程序：{0}", AutoUpdateExeFileName));
                }
                else
                {
                    var zipFile = string.Empty;
                    using (var service = new ServiceObject<IAutoUpdateService>(Util.AutoUpdateServiceAddress))
                    {
                        zipFile = service.Object.GetDefaultSetupFileUrl();
                    }
                    Process.Start(autoUpdateExeFile, zipFile);
                    Process.GetCurrentProcess().Kill();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("对不起，网络连接或者服务器端异常，更新失败！");
            }
        }

        protected void CheckService()
        {
            var canOpen = true;
            try
            {
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    //service.CanOpen();
                    var url = service.Object.GetDownloadInfoUrl();
                    canOpen = !string.IsNullOrEmpty(url);
                    //var dd = service.Object.GetDownloadInfoUrl();
                }
            }
            catch (Exception e)
            {
                canOpen = false;
                //MessageBox.Show(e.Message);
            }
            if (!canOpen)
            {
                MessageBox.Show("对不起，网络连接或者服务器端异常，不能打开软件。");
                Process.GetCurrentProcess().Kill();
            }
        }
        #endregion

    }
}
